import React, { Component } from 'react'
import { connect } from 'react-redux'
import { getList, addCart } from '../../../actions/index'


class Main extends Component {

    componentDidMount() {
        // 请求接口
        if (this.props.list.length === 0) {
            this.props.getlist()
        }
    }

    render() {
        return (
            <div className="wrap main-page">
                {
                    this.props.list.map(item => {
                        return (
                            <dl key={item.id} className="item">
                                <dt>
                                    <img src={item.img} alt="" />
                                </dt>
                                <dd>
                                    <h2>{item.name}</h2>
                                    <p>单价：{item.price}</p>
                                    <button onClick={() => this.props.addCart(item)}>+</button>
                                </dd>
                            </dl>
                        )
                    })
                }
            </div>
        )
    }
}


let mapState = state => {
    return {
        list: state.cart.allList
    }
}

let mapDispatch = dispatch => {
    return {
        getlist() {
            dispatch(getList)
        },
        addCart(info) {
            dispatch(addCart(info))
        }
    }
}

export default connect(mapState, mapDispatch)(Main)
